import "./index.scss"
import TagList from "./_components/tagList"
import {useEffect, useState} from "react";
import {useSearchParams} from "react-router-dom";
import {topPlaylist, playlistType} from "@src/services/music.ts";
import {useRequest} from "ahooks";
import SongListCard from "@src/pages/home/music/_components/songListCard";
import Skeleton from "@src/components/skeleton";
import InView from "@src/components/InView";
import {debounce} from "@src/utils/method.ts"
//分类歌单
export default function CatList() {
    const [search, setSearch] = useSearchParams()
    const [tag, setTag] = useState<string>(search.get("tag") ? search.get("tag") as string : "榜单");
    const topPlaylistApi = useRequest(topPlaylist, {manual: true})
    const [topPlaylistApiData, setTopPlaylistApiData] = useState<playlistType[]>([])
    const [offset, setOffset] = useState(2);

    const AddTopPlaylistApi = debounce(() => {
        if (!topPlaylistApi.loading) {
            setOffset(offset + 1)
        }
    }, 1000);

    useEffect(() => {
        topPlaylistApi.runAsync(tag, 12, offset).then(data => {
            setTopPlaylistApiData((item) => {
                const newItem = [...item, ...data.playlists.slice(1)]
                const uniqueArr = Array.from(new Set(newItem.map(item => item.id))).map(id => {
                    return newItem.find(item => item.id === id);
                });
                return uniqueArr as playlistType[];
            })
        })
    }, [offset]);
    useEffect(() => {
        topPlaylistApi.runAsync(tag).then((data) => {
            setTopPlaylistApiData(data.playlists)
            setOffset(2)
            setSearch({tag})
        })
    }, [tag])


    return <div className="CatList">
        <TagList tag={tag} setTag={setTag}></TagList>
        <div className="play-list">
            <ul>
                <Skeleton loading={topPlaylistApiData.length == 0} style={{aspectRatio: 0.8}}>
                    {topPlaylistApiData.map((item) =>
                        <li key={item.id}><SongListCard playlist={item}></SongListCard></li>)}
                </Skeleton>
            </ul>
            <InView onChange={(e) => {
                if (e) AddTopPlaylistApi()
            }}>
                <div className="text-overflow-1">玩命加载中 (╯°□°）╯︵ ┻━┻</div>
            </InView>
        </div>
    </div>
}